package com.session;

import com.struct.Response;
import com.struct.ResponseHeader;
import com.struct.ResultCode;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Greg.chen on 2016-03-23.
 */
public class SessionManager {

    /**
     * 在线会话
     */
    private static final ConcurrentHashMap<Long, Session> onlineSessions = new ConcurrentHashMap<>();


    /**
     * 加入
     * @param playerId
     * @param session
     * @return
     */
    public static boolean putSession(long playerId, Session session){
        if(!onlineSessions.containsKey(playerId)){
            boolean success = onlineSessions.putIfAbsent(playerId, session)== null? true : false;
            return success;
        }
        return false;
    }

    /**
     * 移除
     * @param playerId
     */
    public static Session removeSession(long playerId){

        return onlineSessions.remove(playerId);
    }


    /**
     * 发送消息[自定义协议]
     * @param playerId
     * @param message
     */
    public static void sendMessage(long playerId, String message){
        Session session = onlineSessions.get(playerId);
        if (session != null && session.isConnected()) {
            Response response = new Response();

            ResponseHeader header = new ResponseHeader();
            header.setUri("/message");
            header.setStateCode(ResultCode.SUCCESS);
            response.setHeader(header);
            response.setBody(message);

            session.write(response);
        }
    }

}
